package indexer;

import java.util.ArrayList;
import domain.Document;
import domain.Post;
import domain.Vocabulary;

public class FileBuffer {
	private Document document;
	private ArrayList<Vocabulary> vocabulary; // the vocabulary of the document

	public FileBuffer() {
	}

	public FileBuffer(Document document, Vocabulary vocabulary) {
		this.document = document;
	}

	/**
	 * builds the vocabulary for the current document
	 * @param document
	 * @param words
	 */
	public void buildVocabulary(Document document, String[] words) {
		if (words == null || words.length == 0)
			return;
		this.document = document;
		document.setNumberOfWords(words.length);
		setLocalVocabulary(words);
	}

	/**
	 * for each word of the document, this method creates an instance of Vocabulary, and
	 * adds it to the vocabulary list of the document
	 * @param words
	 */
	private void setLocalVocabulary(String[] words) {
		this.vocabulary = new ArrayList<Vocabulary>();
		int index = -1;
		for (String word : words) {
			Vocabulary v = new Vocabulary();
			v.setWord(word.trim());
			index = vocabulary.indexOf(v);
			if (index == -1) {
				addNewVocabulary(v);
			} else {
				updateExistentVocabulary(index);
			}
		}
	}

	/**
	 * adds a new vocabulary to the documents vocabulary list
	 * @param v
	 */
	private void addNewVocabulary(Vocabulary v) {
		ArrayList<Post> postList = new ArrayList<Post>();
		Post post = new Post();
		post.setDocument(this.document);
		post.setWordFrequency(1);
		postList.add(post);
		v.setMaxFrequency(1);
		v.setPostList(postList);
		this.vocabulary.add(v);
	}

	/**
	 * update the data of an existent vocabulary of the documents vocabulary list
	 * @param vocIndex
	 */
	private void updateExistentVocabulary(int vocIndex) {
		Post p = new Post();
		p.setDocument(this.document);
		Vocabulary auxVoc = vocabulary.get(vocIndex);
		// increment in one the word frequency of the correspondent post in the post list of
		// the vocabulary
		auxVoc.getPostList().get(0).setWordFrequency(auxVoc.getPostList().get(0).getWordFrequency() + 1);
		auxVoc.setMaxFrequency(auxVoc.getMaxFrequency() + 1);
		auxVoc.setUpdated(true);
	}

	public ArrayList<Vocabulary> getVocabulary() {
		return vocabulary;
	}

	public void setVocabulary(ArrayList<Vocabulary> vocabulary) {
		this.vocabulary = vocabulary;
	}
}
